<?php
defined('IN_PHPCMS') or exit('No permission resources.');
//模型缓存路径
define('CACHE_MODEL_PATH',CACHE_PATH.'caches_model'.DIRECTORY_SEPARATOR.'caches_data'.DIRECTORY_SEPARATOR);
pc_base::load_app_func('util','content');
pc_base::load_sys_class('form', '', 0);
pc_base::load_sys_class('phpqrcode','',0);
class index {
	private $db;
	private $dir;
	function __construct() {
		$this->db = pc_base::load_model('content_model');
		$this->_userid = param::get_cookie('_userid');
		$this->_username = param::get_cookie('_username');
		$this->_groupid = param::get_cookie('_groupid');
		if(isMobile()){
			$this->dir="content_h5";
		}else{
			$this->dir="content";
		}
	}
	//首页
	public function init() {
		if(isset($_GET['siteid'])) {
			$siteid = intval($_GET['siteid']);
		} else {
			$siteid = 1;
		}
		$siteid = $GLOBALS['siteid'] = max($siteid,1);
		define('SITEID', $siteid);
		$_userid = $this->_userid;
		$_username = $this->_username;
		$_groupid = $this->_groupid;
		//SEO
		$SEO = seo($siteid);
		$sitelist  = getcache('sitelist','commons');
		$default_style = $sitelist[$siteid]['default_style'];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');

		include template($this->dir,'index',$default_style);
	}
	//内容页
	public function show() {
		$catid = intval($_GET['catid']);
		$id = intval($_GET['id']);
		$type = $_GET['type']?intval($_GET['type']):1;
		if(!$id) showmessage(L('information_does_not_exist'),'blank');

		$category_source_model = pc_base::load_model('category_source_model');
		$where = 'source_type = '.$type.' and cate_id = '.$catid;
		$pre = $category_source_model->get_one($where.' and source_id<'.$id, 'source_id', 'source_id desc');
		$next = $category_source_model->get_one($where.' and source_id>'.$id, 'source_id', 'source_id asc');

		if ($type == 1) { 
			$types = 1;			//取资讯信息
			$news = file_get_contents(API_URL."/xinsilu/v1/newsNsr/getNewNsrById?id=".$id);
			$news = json_decode($news,true);
			$info = $news['data'];
			//上一篇
			$preInfo = file_get_contents(API_URL."/xinsilu/v1/newsNsr/getNewNsrById?id=".$pre['source_id']);
			$preInfo = json_decode($preInfo,true);
			$previous_page = $preInfo['data'];
			//下一篇
			$nextInfo = file_get_contents(API_URL."/xinsilu/v1/newsNsr/getNewNsrById?id=".$next['source_id']);
			$nextInfo = json_decode($nextInfo,true);
			$next_page = $nextInfo['data'];
		} else if ($type == 2) {
			//取视频信息
			$video = file_get_contents(API_URL."/xinsilu/v1/videoNsr/getVideoNsrById?id=".$id);
			$video = json_decode($video,true);
			$info = $video['data'];
		} else if ($type == 3) { 
			$types = 2;
			//取图集信息
			$pic = file_get_contents(API_URL."/xinsilu/v1/pictureNsr/getPictureNsrById?id=".$id);
			$pic = json_decode($pic,true);
			$info = $pic['data'];
			$pictureurls = json_decode($info['pictureurls'],true);
			//上一篇
			if ($pre['source_id']) {
				$preInfo = file_get_contents(API_URL."/xinsilu/v1/pictureNsr/getPictureNsrById?id=".$pre['source_id']);
				$preInfo = json_decode($preInfo,true);
				$previous_page = $preInfo['data'];
			}
			//下一篇
			if ($next['source_id']) {
				$nextInfo = file_get_contents(API_URL."/xinsilu/v1/pictureNsr/getPictureNsrById?id=".$next['source_id']);
				$nextInfo = json_decode($nextInfo,true);
				$next_page = $nextInfo['data'];
			}
		} else if ($type == 4) { 
			$types = 2;
			//取人才信息
			$talent = file_get_contents(API_URL."/xinsilu/v1/talent/".$id);
			$talent = json_decode($talent,true);
			$info = $talent['data'];
			//取关联图集
			$t_pic = file_get_contents(API_URL."/xinsilu/v1/talent/talentResourceList?max=1&talentId=".$id."&type=3&siteid=1");
			$t_pic = json_decode($t_pic,true);
			if (!empty($t_pic['data'])) {
				$pics = file_get_contents(API_URL."/xinsilu/v1/pictureNsr/getPictureNsrById?id=".$t_pic['data'][0]['id']);
				$pics = json_decode($pics,true);
				$pictureurls = json_decode($pics['data']['pictureurls'],true);
			}
			//上一篇
			if ($pre['source_id']) {
				$preInfo = file_get_contents(API_URL."/xinsilu/v1/talent/".$pre['source_id']);
				$preInfo = json_decode($preInfo,true);
				$previous_page = $preInfo['data'];
				$previous_page['title'] = $previous_page['realName'];
			}
			//下一篇
			if ($next['source_id']) {
				$nextInfo = file_get_contents(API_URL."/xinsilu/v1/talent/".$next['source_id']);
				$nextInfo = json_decode($nextInfo,true);
				$next_page = $nextInfo['data'];
				$next_page['title'] = $next_page['realName'];
			}
		}

		if(!$info){
		    showmessage('您要访问的资源已删除或正在审核中！<br>请稍后再试！', '?m=content&c=index');
		}
		$siteids = getcache('category_content','commons');
		$siteid = $siteids[$catid];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');
		
		//if(!isset($CATEGORYS[$catid]) || $CATEGORYS[$catid]['type']!=0) showmessage(L('information_does_not_exist'),'blank');
		$this->category = $CAT = $CATEGORYS[$catid];
		$this->category_setting = $CAT['setting'] = string2array($this->category['setting']);
		$siteid = $GLOBALS['siteid'] = $CAT['siteid'];
		$setting = $CAT['setting'];
		$template = $setting['show_template'] ? $setting['show_template'] : 'show';
		
		//SEO
		$seo_keywords = '';
		if(!empty($keywords)) $seo_keywords = implode(',',$keywords);
		$SEO = seo($siteid, $catid, $title, $description, $seo_keywords);
		
		// if($rs['paginationtype']!=0) {
		// 	//手动分页
		// 	$CONTENT_POS = strpos($content, '[page]');
		// 	if($CONTENT_POS !== false) {
		// 		$this->url = pc_base::load_app_class('url', 'content');
		// 		$contents = array_filter(explode('[page]', $content));
		// 		$pagenumber = count($contents);
		// 		if (strpos($content, '[/page]')!==false && ($CONTENT_POS<7)) {
		// 			$pagenumber--;
		// 		}
		// 		for($i=1; $i<=$pagenumber; $i++) {
		// 			$pageurls[$i] = $this->url->show($id, $i, $catid, $rs['inputtime']);
		// 		}
		// 		$END_POS = strpos($content, '[/page]');
		// 		if($END_POS !== false) {
		// 			if($CONTENT_POS>7) {
		// 				$content = '[page]'.$title.'[/page]'.$content;
		// 			}
		// 			if(preg_match_all("|\[page\](.*)\[/page\]|U", $content, $m, PREG_PATTERN_ORDER)) {
		// 				foreach($m[1] as $k=>$v) {
		// 					$p = $k+1;
		// 					$titles[$p]['title'] = strip_tags($v);
		// 					$titles[$p]['url'] = $pageurls[$p][0];
		// 				}
		// 			}
		// 		}
		// 		//当不存在 [/page]时，则使用下面分页
		// 		$pages = content_pages($pagenumber,$page, $pageurls);
		// 		//判断[page]出现的位置是否在第一位 
		// 		if($CONTENT_POS<7) {
		// 			$content = $contents[$page];
		// 		} else {
		// 			if ($page==1 && !empty($titles)) {
		// 				$content = $title.'[/page]'.$contents[$page-1];
		// 			} else {
		// 				$content = $contents[$page-1];
		// 			}
		// 		}
		// 		if($titles) {
		// 			list($title, $content) = explode('[/page]', $content);
		// 			$content = trim($content);
		// 			if(strpos($content,'</p>')===0) {
		// 				$content = '<p>'.$content;
		// 			}
		// 			if(stripos($content,'<p>')===0) {
		// 				$content = $content.'</p>';
		// 			}
		// 		}
		// 	}
		// }

		if(empty($previous_page)) {
			$previous_page = array('title'=>L('first_page'), 'thumb'=>IMG_PATH.'nopic_small.gif', 'url'=>'javascript:alert(\''.L('first_page').'\');');
		} else {
			$previous_page['url'] = "/index.php?m=content&c=index&a=show&type=".$type."&catid=".$catid."&id=".$previous_page['id'];
		} 

		if(empty($next_page)) {
			$next_page = array('title'=>L('last_page'), 'thumb'=>IMG_PATH.'nopic_small.gif', 'url'=>'javascript:alert(\''.L('last_page').'\');');
		} else {
			$next_page['url'] = "/index.php?m=content&c=index&a=show&type=".$type."&catid=".$catid."&id=".$next_page['id'];
		}
		include template($this->dir,$template);
	}
	//列表页
	public function lists() {
		$catid = $_GET['catid'] = intval($_GET['catid']);
		// $_priv_data = $this->_category_priv($catid);
		// if($_priv_data=='-1') {
		// 	$forward = urlencode(get_url());
		// 	showmessage(L('login_website'),APP_PATH.'index.php?m=member&c=index&a=login&forward='.$forward);
		// } elseif($_priv_data=='-2') {
		// 	showmessage(L('no_priv'));
		// }
		// $_userid = $this->_userid;
		// $_username = $this->_username;
		// $_groupid = $this->_groupid;

		if(!$catid) showmessage(L('category_not_exists'),'blank');
		$siteids = getcache('category_content','commons');
		$siteid = $siteids[$catid];
		$CATEGORYS = getcache('category_content_'.$siteid,'commons');
		if(!isset($CATEGORYS[$catid])) showmessage(L('category_not_exists'),'blank');
		$CAT = $CATEGORYS[$catid];
		$siteid = $GLOBALS['siteid'] = $CAT['siteid'];
		extract($CAT);
		$setting = string2array($setting);
		//SEO
		if(!$setting['meta_title']) $setting['meta_title'] = $catname;
		$SEO = seo($siteid, '',$setting['meta_title'],$setting['meta_description'],$setting['meta_keywords']);
		define('STYLE',$setting['template_list']);
		$page = $_GET['page']?intval($_GET['page']):1;

		$template = $setting['category_template'] ? $setting['category_template'] : 'category';
		$template_list = $setting['list_template'] ? $setting['list_template'] : 'list';
		
		if($type==0) {
			$template = $child ? $template : $template_list;//echo $template;die;
			// $arrparentid = explode(',', $arrparentid);
			// $top_parentid = $arrparentid[1] ? $arrparentid[1] : $catid;
			// $array_child = array();
			$self_array = explode(',', $arrchildid);
			$child_id = count($self_array) == 1?$self_array[0]:$self_array[1];
			//var_dump($list);die;
			//获取一级栏目ids
			// foreach ($self_array as $arr) {
			// 	if($arr!=$catid && $CATEGORYS[$arr][parentid]==$catid) {
			// 		$array_child[] = $arr;
			// 	}
			// }
			// $arrchildid = implode(',', $array_child);
			// //URL规则
			// $urlrules = getcache('urlrules','commons');
			// $urlrules = str_replace('|', '~',$urlrules[$category_ruleid]);
			// $tmp_urls = explode('~',$urlrules);
			// $tmp_urls = isset($tmp_urls[1]) ?  $tmp_urls[1] : $tmp_urls[0];
			// preg_match_all('/{\$([a-z0-9_]+)}/i',$tmp_urls,$_urls);
			// if(!empty($_urls[1])) {
			// 	foreach($_urls[1] as $_v) {
			// 		$GLOBALS['URL_ARRAY'][$_v] = $_GET[$_v];
			// 	}
			// }
			// define('URLRULE', $urlrules);
			// $GLOBALS['URL_ARRAY']['categorydir'] = $categorydir;
			// $GLOBALS['URL_ARRAY']['catdir'] = $catdir;
			// $GLOBALS['URL_ARRAY']['catid'] = $catid;
			include template($this->dir,$template);
		} else {
		//单网页
			// $this->page_db = pc_base::load_model('page_model');
			// $r = $this->page_db->get_one(array('catid'=>$catid));
			// if($r) extract($r);
			$self_array = explode(',', $arrchildid);
			$child_id = count($self_array) == 1?$self_array[0]:$self_array[1];

			//获取资讯信息
			$info = file_get_contents(API_URL."/xinsilu/v1/column/content/".$child_id."?max=1&type=1&siteid=1");
			$info = json_decode($info,true);
			$infos = file_get_contents(API_URL."/xinsilu/v1/newsNsr/getNewNsrById?id=".$info['data']['returnList'][0]['id']);
			$infos = json_decode($infos,true);
			$news = $infos['data'];//var_dump($news);die;

			$template = $setting['page_template'] ? $setting['page_template'] : 'page';
			$arrchild_arr = $CATEGORYS[$parentid]['arrchildid'];
			if($arrchild_arr=='') $arrchild_arr = $CATEGORYS[$catid]['arrchildid'];
			$arrchild_arr = explode(',',$arrchild_arr);
			array_shift($arrchild_arr);
			$keywords = $keywords ? $keywords : $setting['meta_keywords'];
			$SEO = seo($siteid, 0, $title,$setting['meta_description'],$keywords);
			include template($this->dir,$template);
		}
	}
	
	//JSON 输出
	public function json_list() {
		if($_GET['type']=='keyword' && $_GET['modelid'] && $_GET['keywords']) {
		//根据关键字搜索
			$modelid = intval($_GET['modelid']);
			$id = intval($_GET['id']);

			$MODEL = getcache('model','commons');
			if(isset($MODEL[$modelid])) {
				$keywords = safe_replace(new_html_special_chars($_GET['keywords']));
				$keywords = addslashes(iconv('utf-8','gbk',$keywords));
				$this->db->set_model($modelid);
				$result = $this->db->select("keywords LIKE '%$keywords%'",'id,title,url',10);
				if(!empty($result)) {
					$data = array();
					foreach($result as $rs) {
						if($rs['id']==$id) continue;
						if(CHARSET=='gbk') {
							foreach($rs as $key=>$r) {
								$rs[$key] = iconv('gbk','utf-8',$r);
							}
						}
						$data[] = $rs;
					}
					if(count($data)==0) exit('0');
					echo json_encode($data);
				} else {
					//没有数据
					exit('0');
				}
			}
		}

	}
	
	
	/**
	 * 检查支付状态
	 */
	protected function _check_payment($flag,$paytype) {
		$_userid = $this->_userid;
		$_username = $this->_username;
		if(!$_userid) return false;
		pc_base::load_app_class('spend','pay',0);
		$setting = $this->category_setting;
		$repeatchargedays = intval($setting['repeatchargedays']);
		if($repeatchargedays) {
			$fromtime = SYS_TIME - 86400 * $repeatchargedays;
			$r = spend::spend_time($_userid,$fromtime,$flag);
			if($r['id']) return true;
		}
		return false;
	}
	
	/**
	 * 检查阅读权限
	 *
	 */
	protected function _category_priv($catid) {
		$catid = intval($catid);
		if(!$catid) return '-2';
		$_groupid = $this->_groupid;
		$_groupid = intval($_groupid);
		if($_groupid==0) $_groupid = 8;
		$this->category_priv_db = pc_base::load_model('category_priv_model');
		$result = $this->category_priv_db->select(array('catid'=>$catid,'is_admin'=>0,'action'=>'visit'));
		if($result) {
			if(!$_groupid) return '-1';
			foreach($result as $r) {
				if($r['roleid'] == $_groupid) return '1';
			}
			return '-2';
		} else {
			return '1';
		}
	 }
	 
	 /**
	  * 邀请好友报名页面
	  */
	 public function reg_invite() {
	 	$reg_id = $_GET['regId'] ? intval($_GET['regId']) : 24;
	 	$source = $_GET['source'] ? $_GET['source'] : 'yoyobaby';
	 	$channel = $_GET['channel'] ? $_GET['channel'] : 'yoyobaby';
	 	include template($this->dir,'shop_inviting');
	 }
	 
	 /**
	  * 前台生成二维码
	  * 2017-12-11 16:42:08
	  * angel_in_us
	  **/
	 function create_qrcode(){
	     $info = $_POST;
	     if(!preg_match("/^1[34578]{1}\d{9}$/",$_POST['tel'])){
	     	$result = array();
	     	$result['code'] = "201";
	     	$result['info'] = "手机号码有误,请重输";
	     	echo json_encode($result);
	     	exit();
	     } 
	     $source = $_POST['source'] ? $_POST['source'] : '0';
	     $channel = $_POST['channel'] ? $_POST['channel'] : '0';
	     $data = file_get_contents(API_URL.'/xinsilu/v1/regChildModel/getRootNodeRecommend?regId='.$info['regId'].'&name='.urlencode($info['shop_name']).'&tel='.$info['tel'].'&source='.$source.'&channel='.$channel);
	     echo $data;
	     die;
	 }
	 
	 /**
	  * 根据地址生成二维码
	  * url:报名地址
	  * en_name:英文标识
	  */
	 public function qrcode_image() {
	 	$value = urldecode($_POST['url']); //二维码内容
	 	$errorCorrectionLevel = 'L';//容错级别
	 	$matrixPointSize = 6;//生成图片大小
	 	$saveandprint = true;
	 	$pathname = pc_base::load_config('system','upload_path')."shop_invite";
	 	$filename = $pathname."/".time()."_".rand(1000,9999).".png";
	 	//生成二维码图片
	 	QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2,$saveandprint);
	 	$logo = IMG_PATH.'nsr/nsr_logo.png';//准备好的logo图片
	 	$QR = $filename;//已经生成的原始二维码图
	 	
	 	if ($logo !== FALSE) {
	 		$QR = imagecreatefromstring(file_get_contents($QR));
	 		$logo = imagecreatefromstring(file_get_contents($logo));
	 		$QR_width = imagesx($QR);//二维码图片宽度
	 		$QR_height = imagesy($QR);//二维码图片高度
	 		$logo_width = imagesx($logo);//logo图片宽度
	 		$logo_height = imagesy($logo);//logo图片高度
	 		$logo_qr_width = $QR_width / 5;
	 		$scale = $logo_width/$logo_qr_width;
	 		$logo_qr_height = $logo_height/$scale;
	 		$from_width = ($QR_width - $logo_qr_width) / 2;
	 		//重新组合图片并调整大小
	 		imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
	 				$logo_qr_height, $logo_width, $logo_height);
	 	}
	 	//输出图片
	 	imagepng($QR, $filename);
	 	$filename = str_replace('/data', '',$filename);
	 	echo '<img id="imgOne" class="dyewm" src="'.$filename.'">';
	 	exit();
	 }

    /*
     *通知函-为王璐在APP端配置用
     *2017-12-12 16:37:01
     *angel_in_us
     **/
    public function child_notice()
    {
        //echo '<script>location.href="http://m.nsr.com.cn";</script>';die;
        include template($this->dir,'child_notice');
    }

    /*
     *少儿报名-明日之星挑战赛-为新丝路官网首页轮播跳转链接用
     *2017年12月15日17:03:03
     *angel_in_us
     **/
    public function child_challenge()
    {
        include template($this->dir,'child_challenge');
    }

    /*
     *证书查询-为APP端配置用
     *2018年1月3日14:50:03
     *ningchengshan
     **/
    public function certificate_query()
    {
        include template($this->dir,'certificate_query');
    }
}
?>